//package com.bestcem.xm.ticket.mq;
//
//import cn.hutool.core.collection.CollUtil;
//import cn.hutool.core.date.DatePattern;
//import cn.hutool.core.date.DateUtil;
//import cn.hutool.core.lang.ObjectId;
//import cn.hutool.core.lang.Validator;
//import com.bestcem.xm.common.core.uitls.MsgPackFormatUtil;
//import com.bestcem.xm.ticket.constant.Constants;
//import com.bestcem.xm.ticket.dao.TicketConfigDao;
//import com.bestcem.xm.ticket.dao.TicketDao;
//import com.bestcem.xm.ticket.dao.TicketRecordDao;
//import com.bestcem.xm.ticket.entity.mongo.Ticket;
//import com.bestcem.xm.ticket.entity.mongo.TicketConfig;
//import com.bestcem.xm.ticket.entity.mongo.TicketRecord;
//import com.bestcem.xm.ticket.enums.MemberFootprintTypeEnum;
//import com.bestcem.xm.ticket.enums.TicketOperationTypeEnum;
//import com.bestcem.xm.ticket.grpc.client.TicketBaseQdesGrpcService;
//import com.bestcem.xm.ticket.grpc.client.TicketBaseUserGrpcService;
//import com.bestcem.xm.ticket.grpc.client.TicketUserGrpcService;
//import com.bestcem.xm.ticket.grpc.client.dto.qdes.QdesDTO;
//import com.bestcem.xm.ticket.grpc.client.dto.user.GroupDTO;
//import com.bestcem.xm.ticket.grpc.client.dto.user.GroupNodeDTO;
//import com.bestcem.xm.ticket.mq.dto.FootprintMessage;
//import com.bestcem.xm.ticket.mq.send.biz.TicketMessageSendService;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.Resource;
//import java.io.IOException;
//import java.util.*;
//
///**
// * 工单mq消息生产类
// *
// * @author jy.zhao
// * @version 1.0
// * @date 2021/8/26 17:38
// **/
//@Slf4j
//@Component
//public class TicketMqProductUtil {
//
//    /**
//     * 点分隔符
//     */
//    private static final String POINT_SEPARATOR = "\\.";
//
//    /**
//     * 路由key
//     */
//    private static final String ROUTING_KEY = "";
//
//    /**
//     * 工单记录创建
//     */
//    private static final String TICKET_RECORD_CREATED = "ticket.record.created";
//
//    /**
//     * 工单的状态改变mq
//     */
//    private static final String TICKET_CHANGED = "ticket.changed";
//
//    /**
//     * 工单创建mq
//     */
//    private static final String TICKET_CREATED = "ticket.created";
//
//    /**
//     * 联系人迁移到Java，联系人3.0足迹
//     */
//    private static final String MEMBER_FOOTPRINT_SAVE = "member.footprint_save";
//
//    //    @Resource
////    private RabbitMessageSender rabbitMessageSender;
//    @Resource
//    private TicketUserGrpcService ticketUserGrpcService;
//
//    @Resource
//    private TicketBaseUserGrpcService ticketBaseUserGrpcService;
//
//    @Resource
//    private TicketBaseQdesGrpcService ticketBaseQdesGrpcService;
//
//    @Resource
//    private TicketConfigDao ticketConfigDao;
//
////    @Autowired
////    private RabbitMqConstantConfig rabbitMqConstantConfig;
//
//    @Resource
//    private TicketDao ticketDao;
//
//    @Resource
//    private TicketRecordDao ticketRecordDao;
//    @Autowired
//    private TicketMessageSendService ticketMessageSendService;
//
//    /**
//     * 记录工单的各个进度.mq发送
//     *
//     * @param ticketRecord 工单记录
//     * @author jy.zhao
//     * @date 2021/8/24 14:09
//     **/
//    public void publishTicketRecordCreateMq(Ticket ticket, TicketRecord ticketRecord) {
//        Map<String, Object> mqMsg = getTicketRecordCreateMsg(ticket, ticketRecord);
////        try {
////            rabbitMessageSender.sendMsg(rabbitMqConstantConfig.getAppFanoutExchange(), ROUTING_KEY, TICKET_RECORD_CREATED, mqMsg);
////            if (log.isInfoEnabled()) {
////                log.info("[Ticket] 发送目前消息成功, EXCHANGE_NAME={}, ROUTING_KEY={}, topic={}, mqMsg={}", rabbitMqConstantConfig.getAppFanoutExchange(),
////                        ROUTING_KEY, TICKET_RECORD_CREATED, mqMsg);
////            }
////        } catch (JsonProcessingException e) {
////            log.error("[Ticket] 工单记录创建发送mq消息失败, EXCHANGE_NAME={}, ROUTING_KEY={}, topic={}, mqMsg={}", rabbitMqConstantConfig.getAppFanoutExchange(),
////                    ROUTING_KEY, TICKET_RECORD_CREATED, mqMsg);
////        }
//        ticketMessageSendService.ticketRecordCreatedSend(mqMsg);
//    }
//
//    public void publishTicketRecordCreateMq(Ticket ticket, TicketRecord ticketRecord, String userGroupCode, String surveyNo, String regionName) {
//        Map<String, Object> mqMsg = getTicketRecordCreateMsg(ticket, ticketRecord, userGroupCode, surveyNo, regionName);
////        try {
////            rabbitMessageSender.sendMsg(rabbitMqConstantConfig.getAppFanoutExchange(), ROUTING_KEY, TICKET_RECORD_CREATED, mqMsg);
////            if (log.isInfoEnabled()) {
////                log.info("[Ticket] 发送目前消息成功, EXCHANGE_NAME={}, ROUTING_KEY={}, topic={}, mqMsg={}", rabbitMqConstantConfig.getAppFanoutExchange(),
////                        ROUTING_KEY, TICKET_RECORD_CREATED, mqMsg);
////            }
////        } catch (JsonProcessingException e) {
////            log.error("[Ticket] 发送工单记录mq消息失败, EXCHANGE_NAME={}, ROUTING_KEY={}, topic={}, mqMsg={}", rabbitMqConstantConfig.getAppFanoutExchange(),
////                    ROUTING_KEY, TICKET_RECORD_CREATED, mqMsg);
////        }
//        ticketMessageSendService.ticketRecordCreatedSend(mqMsg);
//
//    }
//
//    /**
//     * 发送工单的mq
//     *
//     * @param ticket    工单信息
//     * @param groupInfo 组织信息
//     * @author jy.zhao
//     * @date 2021/8/24 13:09
//     **/
//    public void publishTicketCreateMQ(Ticket ticket, Map<String, String> groupInfo) {
//        Map<String, Object> mqMsg = getTicketCreateMsg(ticket, groupInfo);
////        try {
////            rabbitMessageSender.sendMsg(rabbitMqConstantConfig.getAppFanoutExchange(), ROUTING_KEY, TICKET_CREATED, mqMsg);
////            if (log.isInfoEnabled()) {
////                log.info("[Ticket] 创建工单发送目前消息成功, EXCHANGE_NAME={}, ROUTING_KEY={}, topic={}, mqMsg={}", rabbitMqConstantConfig.getAppFanoutExchange(),
////                        ROUTING_KEY, TICKET_CREATED, mqMsg);
////            }
////        } catch (JsonProcessingException e) {
////            log.error("[Ticket] 创建工单发送mq消息失败, EXCHANGE_NAME={}, ROUTING_KEY={}, topic={}, mqMsg={}", rabbitMqConstantConfig.getAppFanoutExchange(),
////                    ROUTING_KEY, TICKET_CREATED, mqMsg);
////        }
//        ticketMessageSendService.ticketCreatedFanoutSend(mqMsg);
//    }
//
//    /**
//     * 发送工单变化的mq
//     *
//     * @param ticket 工单信息
//     * @author jy.zhao
//     * @date 2021/8/24 13:09
//     **/
//    public void publishTicketChangeMq(Ticket ticket) {
//        Map<String, Object> mqMsg = getTicketChangeMsg(ticket);
////        try {
////            rabbitMessageSender.sendMsg(rabbitMqConstantConfig.getAppFanoutExchange(), ROUTING_KEY, TICKET_CHANGED, mqMsg);
////            if (log.isInfoEnabled()) {
////                log.info("[Ticket] 发送目前消息成功, EXCHANGE_NAME={}, ROUTING_KEY={}, topic={}, mqMsg={}", rabbitMqConstantConfig.getAppFanoutExchange(),
////                        ROUTING_KEY, TICKET_CHANGED, mqMsg);
////            }
////        } catch (JsonProcessingException e) {
////            log.error("[Ticket] 发送工单状态mq消息失败, EXCHANGE_NAME={}, ROUTING_KEY={}, topic={}, mqMsg={}", rabbitMqConstantConfig.getAppFanoutExchange(),
////                    ROUTING_KEY, TICKET_CHANGED, mqMsg);
////        }
//        ticketMessageSendService.ticketChangedFanoutSend(mqMsg);
//
//    }
//
//    /**
//     * 联系人3.0 p2修改，兼容手动创建工单时关联多个联系人情况
//     *
//     * @param ticket
//     */
//    public void publishMemberFootSaveMqRefactor(Ticket ticket) {
//        // 查询最新的ticket 保证ticket的更新时间最新
//        Ticket nowTicket = ticketDao.findById(ticket.getId());
//        String memberId = nowTicket.getMemberId();
//        if (StringUtils.isNotBlank(memberId)) {
//            String[] split = memberId.split(",");
//            for (String s : split) {
//                if (ObjectId.isValid(s)) {
//                    ticket.setMemberId(s);
//                    this.publishMemberFootSaveMq(nowTicket);
//                }
//            }
//        }
//    }
//
//    public void publishMemberFootSaveMq(Ticket ticket) {
//        if (Validator.isEmpty(ticket.getMemberId())) {
//            log.info("[Ticket] 工单同步到足迹点,没有发现memberid");
//            return;
//        }
//        Map<String, Object> mqMsg = getMemberFootSaveMsg(ticket);
////        try {
//////            rabbitMessageSender.sendMsg(rabbitMqConstantConfig.getAppBpDirectExchange(),
//////                    rabbitMqConstantConfig.getAppBpRoutingKey(), MEMBER_FOOTPRINT_SAVE, mqMsg);
////            FootprintMessage footprintMessage = MsgPackFormatUtil.mapToObj(mqMsg, FootprintMessage.class);
////            memberMessageService.footprintSaveSend(footprintMessage);
////            if (log.isInfoEnabled()) {
////                log.info("[Ticket] 发送mq消息成功, EXCHANGE_NAME={}, ROUTING_KEY={}, topic={}, mqMsg={}", rabbitMqConstantConfig.getAppBpDirectExchange(),
////                        rabbitMqConstantConfig.getAppBpRoutingKey(), MEMBER_FOOTPRINT_SAVE, mqMsg);
////            }
////        } catch (Exception e) {
////            log.error("[Ticket] 发送mq消息失败, EXCHANGE_NAME={}, ROUTING_KEY={}, topic={}, mqMsg={}", rabbitMqConstantConfig.getAppBpDirectExchange(),
////                    rabbitMqConstantConfig.getAppBpRoutingKey(), MEMBER_FOOTPRINT_SAVE, mqMsg);
////        }
//        FootprintMessage footprintMessage = null;
//        try {
//            footprintMessage = MsgPackFormatUtil.mapToObj(mqMsg, FootprintMessage.class);
//        } catch (IOException ignored) {
//        }
//        ticketMessageSendService.footprintSaveSend(footprintMessage);
//    }
//
//    private Map<String, Object> getMemberFootSaveMsg(Ticket ticket) {
//        HashMap<String, Object> content = new HashMap<>();
//        TicketConfig ticketConfig = ticketConfigDao.findById(ticket.getTicketConfigId());
//        TicketRecord lastOneByTicketId = ticketRecordDao.findLastOneByTicketId(ticket.getId());
//        String title = "";
//        if (TicketOperationTypeEnum.MANUAL.getIndex().equals(ticket.getOperationType())) {
//            title = ticket.getName();
//        } else {
//            title = ticketConfig.getTitle();
//        }
//        content.put("title", title);
//        content.put("project_name", ticket.getSurveyTitle());
//        content.put("ticket_status", ticket.getStatus());
//        if (Objects.nonNull(lastOneByTicketId)) {
//            String ticketUpdateTimeStr = DateUtil.format(lastOneByTicketId.getCreatedDate(), DatePattern.NORM_DATETIME_PATTERN);
//            content.put("update_ticket_status_time", Validator.isNotEmpty(ticketUpdateTimeStr) ? ticketUpdateTimeStr : "");
//        } else {
//            String ticketUpdateTimeStr1 = DateUtil.format(ticket.getUpdatedDate(), DatePattern.NORM_DATETIME_PATTERN);
//            content.put("update_ticket_status_time", Validator.isNotEmpty(ticketUpdateTimeStr1) ? ticketUpdateTimeStr1 : "");
//        }
//        HashMap<String, Object> memberFootprintData = new HashMap<>();
//        memberFootprintData.put("org_id", ticket.getOrgId());
//        memberFootprintData.put("member_id", ticket.getMemberId());
//        memberFootprintData.put("type", MemberFootprintTypeEnum.TICKET.getIndex());
//        memberFootprintData.put("source_key", ticket.getId());
//        memberFootprintData.put("content", content);
//        String ticketCreateTimeStr = DateUtil.format(ticket.getCreatedDate(), DatePattern.NORM_DATETIME_PATTERN);
//        memberFootprintData.put("footprint_time", Validator.isNotEmpty(ticketCreateTimeStr) ? ticketCreateTimeStr : "");
//        return memberFootprintData;
//    }
//
//    /**
//     * 获取工单创建、修改消息数据
//     *
//     * @param ticket 工单信息
//     * @return Map<String, Object>
//     * @author jy.zhao
//     * @date 2021/8/26 17:28
//     **/
//    public Map<String, Object> getTicketCreateMsg(Ticket ticket, Map<String, String> groupInfo) {
//        Map<String, Object> mqMsg = new HashMap<>(Constants.DEFAULT_MAP_INITIAL_CAPACITY);
//        mqMsg.put("surveyId", ticket.getSurveyId());
//        mqMsg.put("ticketNo", ticket.getTicketNo());
//        String ticketCreateTimeStr = DateUtil.format(ticket.getCreatedDate(), DatePattern.NORM_DATETIME_MS_PATTERN);
//        mqMsg.put("created_dt", Validator.isNotEmpty(ticketCreateTimeStr) ? ticketCreateTimeStr : "");
//        mqMsg.put("status", ticket.getStatus());
//        mqMsg.put("region", ticket.getRegion());
//        mqMsg.put("code", groupInfo.getOrDefault("userGroupCode", Constants.BLANK));
//        mqMsg.put("regionName", ticket.getRegionName());
//        mqMsg.put("surveyTitle", ticket.getSurveyTitle());
//        mqMsg.put("surveyNo", groupInfo.getOrDefault("surveyCode", Constants.BLANK));
//        mqMsg.put("resId", ticket.getResId());
//        mqMsg.put("id", ticket.getId());
//        mqMsg.put("followRoleId", ticket.getFollowRoleId());
//        mqMsg.put("auditRoleId", ticket.getAuditRoleId());
//
//        if (Validator.isNotEmpty(ticket.getRegion())) {
//            List<GroupNodeDTO> groupNodeDTOList = ticketUserGrpcService.listAncestorGroupsByGroupId(ticket.getRegion());
//            if (CollUtil.isNotEmpty(groupNodeDTOList)) {
//                for (GroupNodeDTO node : groupNodeDTOList) {
//                    mqMsg.put(node.getId(), Optional.ofNullable(node.getTitle()).orElse(Constants.BLANK));
//                }
//            }
//        }
//        return mqMsg;
//    }
//
//    /**
//     * 获取工单创建、修改消息数据
//     *
//     * @param ticket 工单信息
//     * @return Map<String, Object>
//     * @author jy.zhao
//     * @date 2021/8/26 17:28
//     **/
//    public Map<String, Object> getTicketChangeMsg(Ticket ticket) {
//        String userGroupCode = "";
//        if (Validator.isNotEmpty(ticket.getRegion())) {
//            GroupDTO groupDTO = ticketBaseUserGrpcService.getGroup(ticket.getRegion());
//            if (Validator.isNotNull(groupDTO)) {
//                userGroupCode = groupDTO.getCode();
//            }
//        }
//        String surveyNo = "";
//        if (Validator.isNotEmpty(ticket.getSurveyId())) {
//            // 根据问卷id查询问卷项目，得到问卷编号
//            QdesDTO qdesProject = ticketBaseQdesGrpcService.getQdesProject(ticket.getSurveyId());
//            if (Validator.isNotNull(qdesProject)) {
//                surveyNo = qdesProject.getCode();
//            }
//        }
//        Map<String, Object> mqMsg = new HashMap<>(Constants.DEFAULT_MAP_INITIAL_CAPACITY);
//        mqMsg.put("surveyId", ticket.getSurveyId());
//        mqMsg.put("ticketNo", ticket.getTicketNo());
//        String ticketCreateTimeStr = DateUtil.format(ticket.getCreatedDate(), DatePattern.NORM_DATETIME_MS_PATTERN);
//        mqMsg.put("created_dt", Validator.isNotEmpty(ticketCreateTimeStr) ? ticketCreateTimeStr : "");
//        mqMsg.put("status", ticket.getStatus());
//        mqMsg.put("region", ticket.getRegion());
//        mqMsg.put("code", userGroupCode);
//        mqMsg.put("regionName", ticket.getRegionName());
//        mqMsg.put("surveyTitle", ticket.getSurveyTitle());
//        mqMsg.put("surveyNo", surveyNo);
//        mqMsg.put("resId", ticket.getResId());
//        mqMsg.put("id", ticket.getId());
//        mqMsg.put("followRoleId", ticket.getFollowRoleId());
//        mqMsg.put("auditRoleId", ticket.getAuditRoleId());
//
//        if (Validator.isNotEmpty(ticket.getRegion())) {
//            List<GroupNodeDTO> groupNodeDTOList = ticketUserGrpcService.listAncestorGroupsByGroupId(ticket.getRegion());
//            if (CollUtil.isNotEmpty(groupNodeDTOList)) {
//                for (GroupNodeDTO node : groupNodeDTOList) {
//                    mqMsg.put(node.getId(), Optional.ofNullable(node.getTitle()).orElse(Constants.BLANK));
//                }
//            }
//        }
//        return mqMsg;
//    }
//
//    /**
//     * 工单记录创建mq信息
//     *
//     * @param ticket       工单信息
//     * @param ticketRecord 工单记录信息
//     * @return Map<String, Object>
//     * @author jy.zhao
//     * @date 2021/9/2 23:30
//     **/
//    public Map<String, Object> getTicketRecordCreateMsg(Ticket ticket, TicketRecord ticketRecord) {
//        String userGroupCode = "";
//        if (Validator.isNotEmpty(ticket.getRegion())) {
//            GroupDTO groupDTO = ticketBaseUserGrpcService.getGroup(ticket.getRegion());
//            if (Validator.isNotNull(groupDTO)) {
//                userGroupCode = groupDTO.getCode();
//            }
//        }
//        String surveyNo = "";
//        if (Validator.isNotEmpty(ticket.getSurveyId())) {
//            // 根据问卷id查询问卷项目，得到问卷编号
//            QdesDTO surveyProject = ticketBaseQdesGrpcService.getQdesProject(ticket.getSurveyId());
//            if (Validator.isNotNull(surveyProject)) {
//                surveyNo = surveyProject.getCode();
//            }
//        }
//        Map<String, Object> mqMsg = new HashMap<>(Constants.DEFAULT_MAP_INITIAL_CAPACITY);
//        // 问卷id
//        mqMsg.put("surveyId", ticket.getSurveyId());
//        // 工单号
//        mqMsg.put("ticketNo", ticket.getTicketNo());
//        String ticketCreateTimeStr = DateUtil.format(ticket.getCreatedDate(), DatePattern.NORM_DATETIME_MS_PATTERN);
//        // 工单创建时间
//        mqMsg.put("ticket_created_dt", Validator.isNotEmpty(ticketCreateTimeStr) ? ticketCreateTimeStr : "");
//        // 工单状态
//        mqMsg.put("status", ticket.getStatus());
//        // 层级id
//        mqMsg.put("region", ticket.getRegion());
//        //
//        mqMsg.put("code", userGroupCode);
//
//        // 层级名称
//        mqMsg.put("regionName", ticket.getRegionName());
//        // 问卷标题
//        mqMsg.put("surveyTitle", ticket.getSurveyTitle());
//        // 问卷编号
//        mqMsg.put("surveyNo", surveyNo);
//        //
//        mqMsg.put("resId", ticket.getResId());
//        // 工单id
//        mqMsg.put("ticketId", ticket.getId());
//        // 工单事件
//        mqMsg.put("event", ticketRecord.getEvent());
//        // 工单title
//        mqMsg.put("title", ticketRecord.getTitle());
//        // 用户id
//        mqMsg.put("userId", "");
//        // 用户名称
//        mqMsg.put("userName", ticketRecord.getUserName());
//        // 手动还是自动
//        mqMsg.put("source", ticketRecord.getSource());
//        // 角色id
//        mqMsg.put("roleId", Validator.isNotNull(ticketRecord.getRoleId()) ? ticketRecord.getRoleId() : "");
//        // ticketRecordId，日志记录id
//        mqMsg.put("id", ticketRecord.getId());
//        String ticketRecordCreateTimeStr = DateUtil.format(ticketRecord.getCreatedDate(), DatePattern.NORM_DATETIME_MS_PATTERN);
//        // 日志创建时间
//        mqMsg.put("created_dt", Validator.isNotEmpty(ticketRecordCreateTimeStr) ? ticketRecordCreateTimeStr : "");
//        return mqMsg;
//    }
//
//
//    public Map<String, Object> getTicketRecordCreateMsg(Ticket ticket, TicketRecord ticketRecord, String userGroupCode, String surveyNo, String regionName) {
//
//        Map<String, Object> mqMsg = new HashMap<>(Constants.DEFAULT_MAP_INITIAL_CAPACITY);
//        // 问卷id
//        mqMsg.put("surveyId", ticket.getSurveyId());
//        // 工单号
//        mqMsg.put("ticketNo", ticket.getTicketNo());
//        String ticketCreateTimeStr = DateUtil.format(ticket.getCreatedDate(), DatePattern.NORM_DATETIME_MS_PATTERN);
//        // 工单创建时间
//        mqMsg.put("ticket_created_dt", Validator.isNotEmpty(ticketCreateTimeStr) ? ticketCreateTimeStr : "");
//        // 工单状态
//        mqMsg.put("status", ticketRecord.getTicketStatus());
//        // 层级id
//        mqMsg.put("region", ticket.getRegion());
//        //
//        mqMsg.put("code", userGroupCode);
//
//        // 层级名称
//        mqMsg.put("regionName", regionName);
//        // 问卷标题
//        mqMsg.put("surveyTitle", ticket.getSurveyTitle());
//        // 问卷编号
//        mqMsg.put("surveyNo", surveyNo);
//        //
//        mqMsg.put("resId", ticket.getResId());
//        // 工单id
//        mqMsg.put("ticketId", ticket.getId());
//        // 工单事件
//        mqMsg.put("event", ticketRecord.getEvent());
//        // 工单title
//        mqMsg.put("title", ticketRecord.getTitle());
//        // 用户id
//        mqMsg.put("userId", "");
//        // 用户名称
//        mqMsg.put("userName", ticketRecord.getUserName());
//        // 手动还是自动
//        mqMsg.put("source", ticketRecord.getSource());
//        // 角色id
//        mqMsg.put("roleId", Validator.isNotNull(ticketRecord.getRoleId()) ? ticketRecord.getRoleId() : "");
//        // ticketRecordId，日志记录id
//        mqMsg.put("id", ticketRecord.getId());
//        String ticketRecordCreateTimeStr = DateUtil.format(ticketRecord.getCreatedDate(), DatePattern.NORM_DATETIME_MS_PATTERN);
//        // 日志创建时间
//        mqMsg.put("created_dt", Validator.isNotEmpty(ticketRecordCreateTimeStr) ? ticketRecordCreateTimeStr : "");
//        return mqMsg;
//    }
//
//}
